﻿using Entity;
using IService;
using Microsoft.AspNetCore.Mvc;
using Service;

namespace XingWeiDaWMSProject.Controllers
{
    public class SalesOrderController : Controller
    {
        private readonly ISalesOrderService _salesOrderService;


        public SalesOrderController(ISalesOrderService salesOrderService)
        {
            _salesOrderService = salesOrderService;
        }

        public IActionResult Index()
        {
            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                // AJAX请求：返回部分视图（无布局）
                return PartialView();
            }
            else
            {
                // 普通请求：返回完整视图（带布局）
                return View();
            }
        }

        


        public IActionResult Add()
        {
            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                // AJAX请求：返回部分视图（无布局）
                return PartialView();
            }
            else
            {
                // 普通请求：返回完整视图（带布局）
                return View();
            }
        }

        public IActionResult SalesDetail()
        {
            return View();
        }
        [HttpGet] 
        public async Task<ActionResult<List<CustomerSelectDto>>> GetCustomerSelectList()
        {
            try
            {
                // 调用仓储层的异步方法获取数据
                var data = await _salesOrderService.GetCustomerSelectList();

               
                return Ok(data);
            }
            catch (Exception ex)
            {
                // 异常处理：记录日志（实际项目中需添加日志组件）
                // _logger.LogError(ex, "获取客户下拉框列表失败");

                // 失败：返回500状态码和错误信息
                return StatusCode(500, new
                {
                    success = false,
                    message = "获取客户列表失败，请稍后重试",
                    error = ex.Message // 生产环境可移除具体错误信息，避免泄露
                });
            }
        }


        // 新增：获取客户详情接口（供前端调用）
        [HttpGet]
        public async Task<ActionResult> GetCustomerDetail([FromQuery] int customerId)
        {
            try
            {
                var customerDetail = await _salesOrderService.GetCustomerDetailById(customerId);
                if (customerDetail == null)
                {
                    return NotFound(new { message = "客户不存在或已删除" });
                }
                return Ok(new
                {
                    contactPerson = customerDetail.contact_person,
                    contactPhoneNumber = customerDetail.contact_phone_number
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = "获取客户详情失败", error = ex.Message });
            }
        }



        [HttpGet]
        public async Task<ActionResult<List<OrganizationTreeDto>>> GetOrganizationTree()
        {
            try
            {
                var data = await _salesOrderService.GetOrganizationTreeAsync();
                return Ok(data);
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"获取部门树失败：{ex.Message}");
            }
        }


        /// <summary>
        /// 按部门ID获取销售负责人列表（供前端下拉框使用）
        /// </summary>
        /// <param name="deptId">部门ID</param>
        /// <returns>用户下拉框列表</returns>
        [HttpGet]
        public async Task<IActionResult> GetUserByDeptId(int deptId)
        {
            try
            {
                var result = await _salesOrderService.GetUsersByDeptIdAsync(deptId);
                return Ok(result); // 返回200 + 数据
            }
            catch (ArgumentException ex)
            {
             
                return BadRequest(ex.Message); // 参数错误返回400
            }
            catch (Exception ex)
            {
               
                return StatusCode(500, "服务器错误，获取用户列表失败"); // 异常返回500
            }
        }

        /// <summary>
        /// 按用户ID获取所属部门（供前端自动填充部门使用）
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>部门信息</returns>
        [HttpGet]
        public async Task<IActionResult> GetDeptByUserId(int userId)
        {
            try
            {
                var result = await _salesOrderService.GetDeptByUserIdAsync(userId);
                if (result == null)
                    return NotFound("未找到用户所属部门"); // 未找到返回404

                return Ok(result); // 返回200 + 数据
            }
            catch (ArgumentException ex)
            {
                
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                
                return StatusCode(500, "服务器错误，获取部门信息失败");
            }
        }


        //初始化加载所有销售负责人
        [HttpGet]
        public async Task<IActionResult> GetAllPersonInCharge()
        {
            try
            {
                var result = await _salesOrderService.GetAllPersonInChargeAsync();
                return Ok(result);
            }
            catch (Exception ex)
            {
                return StatusCode(500, "获取负责人列表失败");
            }
        }



        [HttpGet]
        public async Task<ActionResult<List<OrganizationTreeDto>>> GetOrganizationTree2(string keyword = "")
        {
            try
            {
                var data = await _salesOrderService.GetOrganizationTreeAsync2(keyword);
                return Ok(data);
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"获取部门树失败：{ex.Message}");
            }
        }




        /// <summary>
        /// 销售货品明细分页显示
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetCustomerPage2 ( string product_code = null,string product_name = null,string unit = null,int currentPage=1,int pageSize = 2)    // 默认每页1条
        {
            try
            {
                // 调用服务层获取分页数据
                var paginationResult = await _salesOrderService.GetAllProductInformationAsync(
                 product_code,product_name,unit,currentPage, pageSize);

                // 返回规范格式（前端可直接解析）
                return Json(new
                {
                    success = true,
                    data = paginationResult.items,  // 当前页数据
                    total = paginationResult.total, // 总条数
                    message = "查询成功"
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    data = new List<SupplierListDTO>(),
                    total = 0,
                    message = $"查询失败：{ex.Message}"
                });
            }

        }

        /// <summary>
        /// 销售订单新增保存功能
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddSalesOrder([FromBody] SalesOrderRequest request)
        {
            try
            {
                // 前端验证：确保明细不为空
                if (request.Details == null || request.Details.Count == 0)
                {
                    return BadRequest(new { success = false, message = "请添加至少一条货品明细" });
                }

                // 调用服务层方法（内部已处理事务和批量插入）
                int salesOrderId = await _salesOrderService.AddSalesOrderWithDetailsAsync(
                    request.Order,    // 主表数据
                    request.Details   // 多条明细数据
                );

                return Ok(new { success = true, message = "订单及明细新增成功", salesOrderId });
            }
            catch (Exception ex)
            {
                return BadRequest(new { success = false, message = ex.Message });
            }
        }



        //销售订单分页查询功能
        [HttpGet]
        public async Task<IActionResult> GetPagedSalesOrders(
           string sales_order_no = null,
           string document_status = null,
           string customer_name = null,
           DateTime? sales_date = null,
           int currentPage = 1,
           int pageSize = 10)
        {
            try
            {
                var result = await _salesOrderService.GetAllWMSOrderSalesOrder2Async(
                    sales_order_no, document_status, customer_name, sales_date, currentPage, pageSize);
                // 返回规范格式（前端可直接解析）
                return Json(new
                {
                    success = true,
                    data = result.items,  // 当前页数据
                    total = result.total, // 总条数
                    message = "查询成功"
                });
               
            }
            catch (Exception ex)
            {
                // 输出异常详情到日志（建议结合日志框架如Serilog/NLog）
                Console.WriteLine($"查询销售订单分页数据异常：{ex.Message}\n{ex.StackTrace}");
                // 返回友好的错误提示
                return StatusCode(500, new { Message = "服务器处理请求时发生异常，请联系管理员", ErrorDetail = ex.Message });
            }
        }


        /// <summary>
        /// 根据销售单号查询销售订单详情
        /// </summary>
        /// <param name="saleOrderNo">销售单号</param>
        /// <returns>销售订单详情实体</returns>
        [HttpGet]
        public async Task<IActionResult> GetSalesOrderDetail(string saleOrderNo)
        {
            if (string.IsNullOrEmpty(saleOrderNo))
            {
                return BadRequest("销售单号不能为空");
            }

            var detail = await _salesOrderService.GetSalesOrderDetailByNo(saleOrderNo);
            if (detail == null)
            {
                return NotFound($"未找到销售单号为【{saleOrderNo}】的订单");
            }

            return Ok(detail);
        }


        /// <summary>
        /// 逻辑删除销售订单
        /// </summary>
        /// <param name="saleOrderNos"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> LogicalDeleteBatch([FromBody] List<string> saleOrderNos)
        {
            if (saleOrderNos == null || !saleOrderNos.Any())
            {
                return BadRequest("请选择要删除的销售单");
            }
            int affectedRows = await _salesOrderService.LogicalDeleteBatch(saleOrderNos);
            return Ok($"批量删除成功，共影响 {affectedRows} 条数据");
        }
        /// <summary>
        /// 批量删除销售订单
        /// </summary>
        /// <param name="saleOrderNo"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> LogicalDeleteSingle([FromBody] string saleOrderNo)
        {
            if (string.IsNullOrEmpty(saleOrderNo))
            {
                return BadRequest("销售单号不能为空");
            }
            int affectedRows = await _salesOrderService.LogicalDeleteSingle(saleOrderNo);
            return Ok($"删除成功，共影响 {affectedRows} 条数据");
        }




        /// <summary>
        /// 批量审核销售订单
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> BatchAuditAsync([FromBody] BatchAuditModel model)
        {
           
            var result = await _salesOrderService.BatchAuditAsync(model.OrderIds, model.AuditResult, model.AuditOpinion, model.Reviewer);
            return Ok(result); // 返回统一格式的AjaxResult
        }

        /// <summary>
        /// 批量撤销销售订单
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> BatchRevokeAsync([FromBody] BatchRevokeModel model)
        {
            var result = await _salesOrderService.BatchRevokeAsync(model.OrderIds);
            return Ok(result);
        }




        // 后端 Controller 新增单条撤销接口
        [HttpPost]
        public async Task<IActionResult> LogicalRevokeSingle([FromBody] int saleOrderId)
        {
            var affectedRows = await _salesOrderService.LogicalRevokeSingle(saleOrderId);
            if (affectedRows > 0)
            {
                return Ok("单条撤销成功");
            }
            return Ok("撤销失败：单据不存在或状态不符");
        }




        /// <summary>
        /// 前端调用的接口：根据部门ID查询人员列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetUsersByOrgId(int orgId, string keyword = "")
        {
            try
            {
                // 控制层仅负责调用服务层，不直接操作数据库
                var users = await _salesOrderService.GetUsersByOrgIdAsync(orgId, keyword);
                return Ok(users);  // 返回JSON格式的人员列表
            }
            catch (System.Exception ex)
            {
                // 异常处理
                return BadRequest($"查询失败：{ex.Message}");
            }
        }

    }

}

